import React, { useEffect, useState } from "react";
import { 
  Col, 
  Row, 
  Card, 
  Table, 
  Button, 
  Form, 
  Input, 
  Select, 
  Upload, 
  message,
  Affix,
  Dropdown,
  Menu
} from "antd";
import * as Icon from '@ant-design/icons';
import { UploadOutlined, CloseOutlined, PlusOutlined, DownOutlined } from '@ant-design/icons';
import './home.css'
import { fetchUserInfo, uploadTorrent, createTorrent } from "../../store/modules/userStore";
import { useDispatch } from "react-redux";

const { Option } = Select;

// table列数据
const columns = [
    {
        title: '序号',
        dataIndex: 'number',
    },
    {
        title: '上传资源名称',
        dataIndex: 'source_name',
    },
    {
        title: '上传时间',
        dataIndex: 'upload_time',
    },
];

// 动态获取icon
const iconToElement = (name) => React.createElement(Icon[name])

const Home = () => {
    const userImg = require("../../assets/images/user_default.png");
    const dispatch = useDispatch();
    const [userInfo, setUserInfo] = useState({});
    const [tableData, setTableData] = useState([]);
    const [showUploadForm, setShowUploadForm] = useState(false);
    const [uploadType, setUploadType] = useState('upload'); // 'upload'或'create'
    const [form] = Form.useForm();
    const [fileList, setFileList] = useState([]);

    useEffect(() => {
        dispatch(fetchUserInfo()).then(res => {
            setUserInfo(res.data);
            localStorage.setItem('userId', res.data.userId);
            localStorage.setItem('passKey', res.data.passKey);
        }).catch(err => {
            console.log("主页获取信息错误：", err);
        });
    }, []);

    // 上传菜单
    const uploadMenu = (
        <Menu onClick={({ key }) => {
            setUploadType(key);
            setShowUploadForm(true);
        }}>
            <Menu.Item key="upload" icon={<UploadOutlined />}>
                上传文件
            </Menu.Item>
            <Menu.Item key="create" icon={<PlusOutlined />}>
                创建种子
            </Menu.Item>
        </Menu>
    );

    // 创建种子时检查文件类型
    const beforeUpload = (file) => {
        if (uploadType === 'create' && !file.name.endsWith('.torrent')) {
            message.error('创建种子必须选择.torrent文件');
            return Upload.LIST_IGNORE;
        }
        return true;
    };

    const handleUpload = async () => {
        try {
            const values = await form.validateFields();
            if (fileList.length === 0) {
                message.error('请选择文件');
                return;
            }

            // 创建种子时额外检查文件类型
            if (uploadType === 'create' && !fileList[0].name.endsWith('.torrent')) {
                message.error('创建种子必须选择.torrent文件');
                return;
            }
     
            const formData = new FormData();
            formData.append('torrentFile', fileList[0].originFileObj);
            formData.append('title', values.title);
            formData.append('description', values.description);
            formData.append('categoryId', values.categoryId);
            formData.append('isAnonymous', values.isAnonymous);
            formData.append('isFreeleech', values.isFreeleech);

            const action = uploadType === 'upload' ? uploadTorrent : createTorrent;
            const res = await dispatch(action(formData));
            if (res.code === 0) {
                message.success(uploadType === 'upload' ? '文件上传成功' : '种子创建成功');
                setShowUploadForm(false);
                form.resetFields();
                setFileList([]);
            } else {
                message.error(res.message || '操作失败');
            }
        } catch (err) {
            console.error('上传错误:', err);
            message.error('操作失败');
        }
    };

    const handleFileChange = (info) => {
        let newFileList = [...info.fileList];
        newFileList = newFileList.slice(-1);
        setFileList(newFileList);
    };

    // 统计数据
    const countData = [
        {
            "name": "总上传资源数量",
            "value": userInfo?.uploaded_delta || 0,
            "icon": "CheckCircleOutlined",
            "color": "#2ec7c9"
        },
        {
            "name": "总下载资源数量",
            "value": userInfo?.downloaded_delta || 0,
            "icon": "CheckCircleOutlined",
            "color": "#ffb980"
        },
        {
            "name": "邀请用户数量",
            "value": "5",
            "icon": "ClockCircleOutlined",
            "color": "#5ab1ef"
        },
        {
            "name": "",
            "value": "",
            "icon": "CheckCircleOutlined",
            "color":"#2ec7c9"
        },
        {
            "name": "",
            "value": "",
            "icon": "CheckCircleOutlined",
            "color":"#ffb980"
        },
        {
            "name": "",
            "value": "",
            "icon": "ClockCircleOutlined",
            "color":"#5ab1ef"
        }
    ];

    return (
        <Row className="home">
            <Col span={8}>
                <Card hoverable>
                    <div className="user">
                        <img src={userInfo?.avatar || userImg} alt="用户头像" />
                        <div className="user-info">
                            <p className="name">{userInfo?.username || "暂无username"}</p>
                            <p className="access">{userInfo?.role || "暂无role"}</p>
                        </div>
                    </div>
                    <div className="login-info">
                        <p>ADDRESS：<span>{userInfo?.address || "暂无address"}</span></p>
                        <p>EMAIL：<span>{userInfo?.email || "暂无email"}</span></p>
                    </div>
                </Card>
                <Card hoverable>
                    <Table 
                        rowKey={"number"} 
                        columns={columns} 
                        dataSource={tableData} 
                        pagination={false}
                    />
                </Card>
            </Col>
            <Col span={16}>
                <div className="num">
                    {countData.map((item, index) => (
                        <Card key={index}>
                            <div className="icon-box" style={{ background: item.color }}>
                                {iconToElement(item.icon)}
                            </div>
                            <div className="detail">
                                <p className="num">{item.value}</p>
                                <p className="txt">{item.name}</p>
                            </div>
                        </Card>
                    ))}
                </div>
            </Col>

            {/* 右下角悬浮上传按钮和表单 */}
            <Affix style={{ position: 'fixed', right: 24, bottom: 24 }}>
                {!showUploadForm ? (
                    <Dropdown overlay={uploadMenu} trigger={['hover']}>
                        <Button 
                            type="primary" 
                            shape="circle" 
                            size="large"
                            icon={<UploadOutlined />}
                            className="floating-upload-btn"
                        />
                    </Dropdown>
                ) : (
                    <Card 
                        title={uploadType === 'upload' ? '上传文件' : '创建种子'} 
                        className="upload-form-card"
                        extra={
                            <CloseOutlined 
                                onClick={() => {
                                    setShowUploadForm(false);
                                    form.resetFields();
                                    setFileList([]);
                                }} 
                            />
                        }
                    >
                        <Form form={form} layout="vertical">
                            <Form.Item
                                name="torrentFile"
                                label={uploadType === 'upload' ? '选择文件' : '选择种子文件(.torrent)'}
                                rules={[{ required: true, message: '请选择文件' }]}
                            >
                                <Upload
                                    beforeUpload={beforeUpload}
                                    onChange={handleFileChange}
                                    fileList={fileList}
                                    maxCount={1}
                                    accept={uploadType === 'create' ? '.torrent' : undefined}
                                >
                                    <Button icon={<UploadOutlined />}>
                                        {uploadType === 'upload' ? '选择文件' : '选择.torrent文件'}
                                    </Button>
                                </Upload>
                            </Form.Item>
                            <Form.Item
                                name="title"
                                label="标题"
                                rules={[{ required: true, message: '请输入标题' }]}
                            >
                                <Input placeholder="请输入标题" />
                            </Form.Item>
                            <Form.Item
                                name="description"
                                label="描述"
                                rules={[{ required: true, message: '请输入描述' }]}
                            >
                                <Input.TextArea rows={4} placeholder="请输入描述" />
                            </Form.Item>
                            <Row gutter={16}>
                                <Col span={8}>
                                    <Form.Item
                                        name="categoryId"
                                        label="分类"
                                        rules={[{ required: true, message: '请选择分类' }]}
                                    >
                                        <Select placeholder="请选择分类">
                                            <Option value={1}>电影</Option>
                                            <Option value={2}>电视剧</Option>
                                            <Option value={3}>音乐</Option>
                                            <Option value={4}>游戏</Option>
                                            <Option value={5}>软件</Option>
                                        </Select>
                                    </Form.Item>
                                </Col>
                                <Col span={8}>
                                    <Form.Item
                                        name="isAnonymous"
                                        label="是否匿名"
                                        rules={[{ required: true, message: '请选择是否匿名' }]}
                                    >
                                        <Select placeholder="请选择是否匿名">
                                            <Option value={true}>是</Option>
                                            <Option value={false}>否</Option>
                                        </Select>
                                    </Form.Item>
                                </Col>
                                <Col span={8}>
                                    <Form.Item
                                        name="isFreeleech"
                                        label="是否免费"
                                        rules={[{ required: true, message: '请选择是否免费' }]}
                                    >
                                        <Select placeholder="请选择是否免费">
                                            <Option value={true}>是</Option>
                                            <Option value={false}>否</Option>
                                        </Select>
                                    </Form.Item>
                                </Col>
                            </Row>
                            <Button 
                                type="primary" 
                                onClick={handleUpload}
                                style={{ marginTop: 16, width: '100%' }}
                            >
                                {uploadType === 'upload' ? '上传文件' : '创建种子'}
                            </Button>
                        </Form>
                    </Card>
                )}
            </Affix>
        </Row>
    );
};

export default Home;